local hlan={}


local hlan_data = {
    rbuff = {},
    rbuff_len = 0,
    strbuff = "",
}
local hlan_cfg = {
    uid = 11,
    baud = 115200,
    data = 8,
    stop = 1,
    parity = uart.NONE,
}

-------------------------串口-------------------------
function hlan.write(s)
    -- log.info("uart1 write",s:toHex())
    uart.write(hlan_cfg.uid, s)
end

-- 串口接收数据处理任务
local function hlan_read()
    local cacheData = ""
    local s
    repeat
        s = uart.read(hlan_cfg.uid, 1)
        if #s > 0 then
            cacheData = cacheData .. s
        else
            if cacheData:len() > 0 then
                local a, _ = string.toHex(cacheData)
                log.info("[hlan]->rev:", #cacheData)
                -- 用户逻辑处理代码
                table.insert(hlan_data.rbuff, cacheData)
                hlan_data.rbuff_len = hlan_data.rbuff_len + #cacheData
                if hlan_data.rbuff_len > 29200 then
                    hlan_data.rbuff = {}
                    hlan_data.rbuff_len = 0
                end
                h485.Sensor_val.lan_flag = 1
                cacheData = ""
            end
        end
    until s == ""
end

uart.on(hlan_cfg.uid, "receive", hlan_read)
--配置并且打开串口
uart.setup(hlan_cfg.uid, hlan_cfg.baud, hlan_cfg.data, hlan_cfg.stop)

-- 启动LAN串口数据接收任务
sys.taskInit(function()
    local send_buff = ""
    while true do
        if hlan_data.rbuff_len > 0 then
            hlan_data.strbuff = table.concat(hlan_data.rbuff)
            hlan_data.rbuff = {}
            hlan_data.rbuff_len = 0
            if h485.cmd_parse(hlan_data.strbuff) == 0 then
                send_buff = h232.serial2dtu(hlan_data.strbuff)
                if send_buff ~= "" then
                    log.debug("[hlan]->send buff:", #send_buff)
                    -- hsocket.hsocket_send(send_buff,0,1)
                    -- tf.tf_write_data("[hlan]",send_buff)
                    h232.write(send_buff)
                    send_buff = ""
                    hlan_data.strbuff = ""
                end
            else
                hlan.write(h485.print_hconfig_net())
            end
        end
        sys.wait(1000)
    end
end)


return hlan